const db = require("./database.js")

async function selectOrderListByUserId(user_id) {
  return new Promise((resolve, reject) => {
    db.all('select * from yr_order where user_id = ? order by create_time desc', [user_id], (err, rows) => {
      if (err) {
        reject(err);
      } else {
        resolve(rows);
      }
    })
  })
}

async function selectOrderByOrderId(order_id) {
  return new Promise((resolve, reject) => {
    db.get('select * from yr_order where order_id = ?', [order_id], (err, row) => {
      if (err) {
        reject(err);
      } else {
        resolve(row);
      }
    })
  })
}

async function insertOrder(order) {
  return new Promise((resolve, reject) => {
    db.run('insert into yr_order(order_id, user_id, name, address, phone_number, price, status, create_time) values (?,?,?,?,?,?,?,?)', [order.order_id, order.user_id, order.name, order.address, order.phone_number, order.price, order.status, order.create_time], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    })
  })
}

async function selectOrderProdByOrderId(order_id) {
  return new Promise((resolve, reject) => {
    db.all('select o.order_id, o.price, o.amount, p.prod_id, p.title, p.info, p.img from yr_order_prod o left join prod p on o.prod_id = p.prod_id where o.order_id = ?', [order_id], (err, rows) => {
      if (err) {
        reject(err);
      } else {
        resolve(rows);
      }
    })
  })
}

async function insertOrderProd(prod) {
  return new Promise((resolve, reject) => {
    db.run('insert into yr_order_prod(order_id, prod_id, price, amount) values (?,?,?,?)', [prod.order_id, prod.prod_id, prod.price, prod.amount], (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    })
  })
}

async function updateOrderStatus(order) {
  return new Promise((resolve, reject) => {
    db.run('update yr_order set status = ? where order_id = ?', [order.status, order.order_id], (err) => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    })
  })
}

module.exports = {
  selectOrderByOrderId,
  selectOrderListByUserId,
  insertOrder,
  selectOrderProdByOrderId,
  insertOrderProd,
  updateOrderStatus
}
